package com.wolf.etl.core.loadbalance;

import com.wolf.etl.core.ETLManager;
import com.wolf.etl.core.task.TaskStatus;
import com.wolf.etl.model.EtlDefineModel;
import com.wolf.etl.model.EtlInstanceModel;
import com.wolf.etl.model.EtlTaskModel;
import com.wolf.util.NumberUtil;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 负载均衡管理
 *
 * @author sdyang
 * @date 2019/12/5 14:32
 **/
@Service("loadBalanceManage")
public class LoadBalanceManage {

    public void init(ETLManager manager) {
        List<EtlTaskModel> tasks = manager.findTaskByStatus(TaskStatus.ENABLE);

        for (EtlTaskModel task : tasks) {
            Long define_id = task.getEtl_define_id();

            EtlDefineModel define = manager.findDefineById(define_id);

            // 统计记录数量
            manager.count(define_id);
            define = manager.findDefineById(define_id);


            List<EtlInstanceModel> instances = manager.findInstancesByDefineId(define_id);

            String strategy = define.getLoad_balance_strategy();

            Class<?> clazz = null;
            try {
                Long pageNum = (define.getRecord_count() - 1) / define.getFetch_max_count() + 1;
                clazz = Class.forName(String.format("%s.%sBalance", getPackageName(), strategy));
                AbstractLoadBalance loadBalance = (AbstractLoadBalance) manager.getBeanManager().createBean(clazz);
                instances = loadBalance.select(instances, pageNum.intValue());
                for (EtlInstanceModel instance : instances) {
                    manager.updateInstance(instance);
                }

            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

    }

    private static final String getPackageName() {
        return new Object() {
            public String getClassForStatic() {
                return this.getClass().getPackage().getName();
            }
        }.getClassForStatic();
    }
}
